package com.my.iot.protocol.modbus.tcp;


import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.ip.IpParameters;
import lombok.Getter;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangjixin
 */
@Component
@Log4j2
public class ModbusTcpConnect {


    private final ModbusFactory modbusFactory = new ModbusFactory();

    // 添加受保护的 getter 方法供测试使用
    @Getter
    private final Map<String, ModbusMaster> tcpMasters = new HashMap<>();

    private static final List<ModbusTcpConfig> TCP_CONNECTIONS = new ArrayList<>();


    //模拟modbusTCP连接配置  后续可以配置在数据库
    static {
        TCP_CONNECTIONS.add(new ModbusTcpConfig()
                .setHost("192.168.124.49")
                .setPort(502));
    }

    /**
     * 初始化TCP连接
     */
    @PostConstruct
    public String init() {
        TCP_CONNECTIONS.forEach(item -> {
            String key = item.getHost() + ":" + item.getPort();
            IpParameters ipParameters = new IpParameters();
            ipParameters.setHost(item.getHost());
            ipParameters.setPort(item.getPort());
            ModbusMaster tcpMaster = modbusFactory.createTcpMaster(ipParameters, true);
            try {
                tcpMaster.init();
                tcpMasters.put(key, tcpMaster);
                log.info("Successfully initialized Modbus master for {}:{}", key, item);
            } catch (ModbusInitException e) {
                log.error("Failed to initialize Modbus master for {}: {}", key, e.getMessage());
            }
        });
        return "连接成功";


    }


    /**
     * 销毁TCP连接
     */
    @PreDestroy
    public void destroy() {
        tcpMasters.values().forEach(master -> {
            try {
                master.destroy();
            } catch (Exception e) {
                log.error("Failed to destroy Modbus master: {}", e.getMessage(), e);
            }
        });
        tcpMasters.clear();
    }

}
